package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;

//用户
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HttpSession httpSession;

    @Override
    public User login(String phone,String code) {
        //判断code是否与seesion中的验证码一样
        String sesson_code = (String) httpSession.getAttribute("SMS_" + phone);
        System.out.println(code);
        System.out.println(sesson_code);
        if (!StringUtils.equals(code, sesson_code)
                || StringUtils.isEmpty(code)
                || StringUtils.isEmpty(sesson_code)) {
            return null;
        }
            //首先要根据电话查询是否存在，存在就返回登录成功
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userMapper.selectOne(queryWrapper);
            if (user == null){
                //不存在就转为注册，也就是向表中添加数据
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userMapper.insert(user);
            }
        //将user信息保存到session中(注意: 这个键必须跟拦截器中使用的键一致)
        httpSession.setAttribute("SESSION_USER", user);
        return user;
    }
}
